package com.wswy.wyjk.ui.main.choose

import android.arch.lifecycle.LiveData
import android.arch.lifecycle.MutableLiveData
import com.raft.framework.arch.BaseViewModel
import com.raft.framework.utils.AssetUtils
import com.raft.framework.utils.RxUtils
import com.raft.framework.utils.optional.Optional
import com.wswy.wyjk.AppContext
import com.wswy.wyjk.model.CityModel
import com.wswy.wyjk.utils.JsonKit
import io.reactivex.Single

class CityLoadViewModel : BaseViewModel() {


    private val wzCityLiveData = MutableLiveData<Map<String, MutableList<CityModel>>>()

    fun loadWZCity() {

        val subscribe = Single.fromCallable {

            val ret = kotlin.runCatching {

                JsonKit.GSON.fromJson(
                    AssetUtils.read2String(AppContext.getContext(), "city-list.json"),
                    CityListResp::class.java
                )

            }
            Optional.ofNullable(ret.getOrNull())
        }.compose(RxUtils.io2main())
            .subscribe { t1, t2 ->

                val ret = mutableMapOf<String, MutableList<CityModel>>()

                t1?.orNull()?.run {
                    directCityList?.forEach {

                        ret.getOrPut(it.nameLatter) {
                            mutableListOf()
                        }.add(it)

                    }

                    cityList?.forEach {

                        it.list?.forEach {
                            ret.getOrPut(it.nameLatter) {
                                mutableListOf()
                            }.add(it)
                        }

                    }

                    wzCityLiveData.postValue(ret)
                }

            }

        addRun(subscribe)

//        val map = Api.get().cityList().compose(RxUtils.switch2io()).map {
//
//            val ret  = mutableMapOf<String,MutableList<WZCity>>()
//
//            it.orNull()?.run {
//
//                directCityList?.forEach {
//
//                    ret.getOrPut(it.nameLatter){
//                        mutableListOf()
//                    }.add(it)
//
//                }
//
//                cityList?.forEach {
//
//                    it.list?.forEach {
//                        ret.getOrPut(it.nameLatter){
//                            mutableListOf()
//                        }.add(it)
//                    }
//
//                }
//
//            }
//
//            return@map Optional.of(ret.toMap())
//        }
//        addRun(map.onResult(wzCityLiveData))
    }


    fun getWZCityLiveData(): LiveData<Map<String, MutableList<CityModel>>> = wzCityLiveData

}